import { Component, OnInit, OnDestroy, ViewChild } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { DatePipe } from '@angular/common';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { BehaviorSubject, Observable, of } from 'rxjs';
import { catchError, debounceTime, map, switchMap } from 'rxjs/operators';
import { NzModalService } from 'ng-zorro-antd/modal';

import { rentplaneMachineStatusArrs, rentplaneDeviceTypeArrs, rentplaneOutTypeArrs } from '../used-rentplane-manage.pipe';
import { CommonService } from '../../../../services-common/common.service';
import { UsedRentplaneManageService } from '../services/used-rentplane-manage.service';

@Component({
  selector: 'app-used-rentplane-list',
  templateUrl: './used-rentplane-list.component.html',
  styleUrls: ['./used-rentplane-list.component.scss'],
  providers: [DatePipe]
})
export class UsedRentplaneListComponent implements OnInit, OnDestroy {
  @ViewChild('followUpRef') followUpRef: any;

  disabledStartDate = (startValue: Date): boolean => {
    if (!startValue || !this.validateForm.value.warrantyEndTime) {
      return false;
    }
    return startValue.getTime() > new Date(this.validateForm.value.warrantyEndTime).getTime();
  };

  disabledEndDate = (endValue: Date): boolean => {
    if (!endValue || !this.validateForm.value.warrantyStartTime) {
      return false;
    }
    return endValue.getTime() <= new Date(this.validateForm.value.warrantyStartTime).getTime();
  };

  statusOptions: any = [...rentplaneMachineStatusArrs];
  deviceOptions: any = [...rentplaneDeviceTypeArrs]; // 设备类型
  outOptions: any = [...rentplaneOutTypeArrs]; // 出库类型
  searchOptions = [
    { type: 1, labelText: '机器', valueKey: 'code', value: '', placeholder: '编码/SN/IMEI' },
    {
      type: 2,
      labelText: '状态',
      valueKey: 'status',
      value: [],
      multiple: true,
      selectBindKey: { key: 'value', label: 'label' },
      selectOptions: this.statusOptions,
    },
    {
      type: 21,
      labelText: '机型',
      valueKey: 'modelIds',
      value: '',
      multiple: false,
      selectBindKey: { key: 'id', label: 'name' },
      selectOptions: [],
      isSelectSearchLoading: false,
      selectSearchChange: (val: any) => {
        this.orderCodeSearch(val);
      }
    },
    { type: 1, labelText: '租机备注', valueKey: 'rentBak', value: '' },
    { type: 1, labelText: '采购备注', valueKey: 'purchaseBak', value: '' },
    { type: 3, labelText: '入库时间', valueKey: ['wtime', 'wtime2'], value: [], isTimeSelect: true },
    { type: 3, labelText: '出库时间', valueKey: ['otime', 'otime2'], value: [], isTimeSelect: true },
  ];
  searchParams: any = {};

  // search
  searchChange$ = new BehaviorSubject('');

  tableParams: any = {
    loading: false,
    tableData: [],
    page: 1,
    pageSize: 20,
    total: 0
  };

  exportLoading = false;

  // options
  brandOptions: any = [];
  seriesOptions: any = [];
  modelOptions: any = [];
  colorOptions: any = [];
  memoryOptions: any = [];

  // 新增 | 编辑 | 复制 Modal
  isModalSpinning = true;
  isVisible = false;
  submitLoading = false;
  uploadLoading = false;
  formLabel = 5;
  formControl = 19;
  validateForm!: FormGroup;
  modelType: number = 0;
  modelItem: any = {};
  fileList: any[] = [];

  // 跟进 Modal
  initParams: any = {
    type: 10, // type  1、订单 2、售后 3、客户 4、出库 5、直降 6、退税 7、机器 8、商品
    modelId: 2, // 类型 1、旧的表示二手回收 2、表示二手商城 3、表示二手回收
    relationInformation: ''
  };

  constructor(
    private message: NzMessageService,
    private fb: FormBuilder,
    private commonService: CommonService,
    private datePipe: DatePipe,
    private modal: NzModalService,
    private services: UsedRentplaneManageService
  ) { }

  ngOnInit(): void {
    this.validateForm = this.fb.group({
      status: ['', [Validators.required]], // 状态
      equipmentCode: [''], // 机器编码
      serialNumber: ['', [Validators.required]], // 序列号SN
      imei: [''], // IMEI
      deviceTypeId: ['', [Validators.required]], // 设备类型
      isSupervised: ['', [Validators.required]], // 监管状态
      imei2: [''], // imei2
      outType: [''], // 出库类型
      warrantyStartTime: [''], // 保修开始时间
      warrantyEndTime: [''], // 保修结束时间
      relationNo: [''], // 关联单号
      typeId: [''], // 品牌
      typeName: [''], // 品牌名称
      seriesId: [''], // 系列
      seriesName: [''], // 系列名称
      modelId: [''], // 机型
      modelName: [''], // 机型名称
      color: [''], // 颜色
      memory: [''], // 内存
      purchasePrice: [''], // 采购价
      purchaseBak: [''], // 采购备注
      rentOrderNo: [''], // 租机订单号
      rentShipNo: [''], // 租机发货单号
      rentUserName: [''], // 租机用户名
      rentUserPhone: [''], // 租机用户电话
      rentBak: [''], // 租机备注
      wtime: [''], // 入库时间
      otime: [''], // 出库时间
      attach: [[]] // 附件
    });

    // 系列名称下拉 防抖
    this.searchChange$
      .asObservable()
      .pipe(debounceTime(500))
      .subscribe((value: any) => {
        if (!value) {
          let searchIndex = this.searchOptions.findIndex((item: any) => item.valueKey === 'modelIds');
          this.searchOptions[searchIndex].selectOptions = [];
          return
        }
        this.loadOrderCodeOptions(value);
      })
  }

  ngOnDestroy(): void {
    this.searchChange$.unsubscribe();
  }

  // Search 机型
  async loadOrderCodeOptions(seriesName?: string) {
    let searchIndex = this.searchOptions.findIndex((item: any) => item.valueKey === 'modelIds');
    let params = {
      name: seriesName || '',
      page: 1,
      pageSize: 99999
    }

    this.searchOptions[searchIndex].isSelectSearchLoading = true;
    const res: any = await this.commonService.getModelList(params);
    this.searchOptions[searchIndex].isSelectSearchLoading = false;
    if (res.code === 0) {
      const { records, total } = res.data || {};
      this.searchOptions[searchIndex].selectOptions = records || [];
    } else {
      this.searchOptions[searchIndex].selectOptions = [];
    }
  }
  orderCodeSearch(value: any) {
    this.searchChange$.next(value);
  }

  async loadTable() {
    let params = {
      ...this.searchParams,
      page: this.tableParams.page,
      pageSize: this.tableParams.pageSize
    }
    this.tableParams.loading = true;
    const {code, data, message}: any = await this.services.queryNewMachineList(params);
    this.tableParams.loading = false;

    if (code === 0) {
      const {records, total} = data || {};
      this.tableParams.tableData = records || [];
      this.tableParams.total = total || 0;

      if (this.tableParams?.tableData?.length) {
        this.tableParams.tableData.map((item: any) => {
          item.attachLists = item?.attach ? JSON.parse(item.attach) : []
        })
      }
    } else {
      this.message.error(message);
    }
  }

  queryResetData(params: any) {
    this.searchParams=  params;
    this.tableParams.page = 1;
    this.loadTable();
  }

  // PageIndex Change
  onPageIndexChange(index: number) {
    this.tableParams.page = index;
    this.loadTable();
  }

  // PageSize Change
  onPageSizeChange(sizeNum: number) {
    this.tableParams.page = 1;
    this.tableParams.pageSize = sizeNum;
    this.loadTable();
  }

  /**
   * ----------------------------------------------------------------
   * 新增 | 编辑 | 复制 Modal
   * ----------------------------------------------------------------
   */
  async loadModalData() {
    this.isModalSpinning = true;
    this.validateForm.get('status')?.setValue(this.modelItem.status); // 状态
    this.validateForm.get('equipmentCode')?.setValue(this.modelItem.equipmentCode); // 机器编码
    this.validateForm.get('serialNumber')?.setValue(this.modelItem.serialNumber); // 序列号SN
    this.validateForm.get('imei')?.setValue(this.modelItem.imei); // IMEI

    this.validateForm.get('deviceTypeId')?.setValue(this.modelItem.deviceTypeId ? Number(this.modelItem.deviceTypeId) : ''); // 设备类型
    this.validateForm.get('isSupervised')?.setValue(!this.commonService.isEmpty(this.modelItem.isSupervised) ? Number(this.modelItem.isSupervised) : ''); // 监管状态
    this.validateForm.get('imei2')?.setValue(this.modelItem.imei2); // imei2
    this.validateForm.get('outType')?.setValue(!this.commonService.isEmpty(this.modelItem.outType) ? Number(this.modelItem.outType) : ''); // 出库类型
    this.validateForm.get('warrantyStartTime')?.setValue(this.modelItem.warrantyStartTime); // 保修开始时间
    this.validateForm.get('warrantyEndTime')?.setValue(this.modelItem.warrantyEndTime); // 保修结束时间
    this.validateForm.get('relationNo')?.setValue(this.modelItem.relationNo || ''); // 关联单号

    this.validateForm.get('typeId')?.setValue(this.modelItem.typeId); // 品牌
    this.validateForm.get('typeName')?.setValue(this.modelItem.typeName); // 品牌名称
    if (this.validateForm.value.typeName) {
      await this.querySeriesOption();
    }
    this.validateForm.get('seriesId')?.setValue(this.modelItem.seriesId); // 系列
    this.validateForm.get('seriesName')?.setValue(this.modelItem.seriesName); // 系列名称
    if (this.validateForm.value.seriesName) {
      await this.queryModelOption();
    }
    this.validateForm.get('modelId')?.setValue(this.modelItem.modelId); // 机型
    this.validateForm.get('modelName')?.setValue(this.modelItem.modelName); // 机型名称
    this.validateForm.get('color')?.setValue(this.modelItem.color); // 颜色
    this.validateForm.get('memory')?.setValue(this.modelItem.memory); // 内存
    this.validateForm.get('purchasePrice')?.setValue(this.modelItem.purchasePrice); // 采购价
    this.validateForm.get('purchaseBak')?.setValue(this.modelItem.purchaseBak); // 采购备注
    this.validateForm.get('rentOrderNo')?.setValue(this.modelItem.rentOrderNo); // 租机订单号
    this.validateForm.get('rentShipNo')?.setValue(this.modelItem.rentShipNo); // 租机发货单号
    this.validateForm.get('rentUserName')?.setValue(this.modelItem.rentUserName); // 租机用户名
    this.validateForm.get('rentUserPhone')?.setValue(this.modelItem.rentUserPhone); // 租机用户电话
    this.validateForm.get('rentBak')?.setValue(this.modelItem.rentBak); // 租机备注
    this.validateForm.get('wtime')?.setValue(this.modelItem.wtime); // 入库时间
    this.validateForm.get('otime')?.setValue(this.modelItem.otime); // 出库时间
    this.validateForm.get('attach')?.setValue(this.modelItem.attach); // 附件
    this.fileList = this.modelItem.attach ? JSON.parse(this.modelItem.attach) : []; // 附件List
    this.isModalSpinning = false;
  }

  showModal(type: number, item?: any) {
    this.isModalSpinning = false;
    this.modelType = type;
    this.queryBrandOption();
    this.validateForm.reset();
    this.fileList = [];

    if ([1, 2].includes(type)) {
      this.modelItem = item || {};
      this.loadModalData();
    }
    this.isVisible = true;
  }

  submitForm(): void {
    if (this.validateForm.valid) {
      this.submitInterface();
    } else {
      Object.values(this.validateForm.controls).forEach(control => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({ onlySelf: true });
        }
      });
    }
  }

  async submitInterface() {
    let params = {
      ...this.validateForm.value,
      warrantyStartTime: this.datePipe.transform(this.validateForm.value.warrantyStartTime, 'yyyy-MM-dd HH:mm:ss'),
      warrantyEndTime: this.datePipe.transform(this.validateForm.value.warrantyEndTime, 'yyyy-MM-dd HH:mm:ss'),
      wtime: this.datePipe.transform(this.validateForm.value.wtime, 'yyyy-MM-dd HH:mm:ss'),
      otime: this.datePipe.transform(this.validateForm.value.otime, 'yyyy-MM-dd HH:mm:ss'),
      attach: this.fileList.length ? JSON.stringify(this.fileList) : ''
    }
    if (this.modelType === 1) {
      params.id = this.modelItem.id
    }

    for (let key in params) {
      if (this.commonService.isEmpty(params[key])) {
        if (Array.isArray(params[key])) {
          params[key] = [];
        } else {
          params[key] = '';
        }
      }
    }
    
    this.submitLoading = true;
    const {code, message}: any = await this.services.saveNewMachineData(params);
    this.submitLoading = false;
    if (code === 0) {
      this.isVisible = false;
      this.message.success('操作成功');
      this.loadTable();
    } else {
      this.message.error(message);
    }
  }

  // 导出
  exportTable() {
    if (!this.tableParams.tableData.length) {
      this.message.warning('暂无可导出数据!');
      return
    }
    
    this.modal.confirm({
      nzTitle: '提示',
      nzContent: '即将导出符合本页面筛选条件的数据，为了导出速度请尽可能的控制时间范围。确认导出？',
      nzOkText: '确认',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: async () => {
        let params = {
          ...this.searchParams
        }
        this.exportLoading = true;
        const res: any = await this.services.exportNewMachineData(params);
        this.exportLoading = false;
    
        if (res.type === 'application/octet-stream') {
          this.commonService.downLoadBlobFile(res, '租机机器管理');
        } else {
          this.message.error('导出失败');
        }
      },
      nzCancelText: '取消'
    });
  }

  // 跟进
  followModal(item: any) {
    this.initParams.relationInformation = item.id;
    this.followUpRef.isModelVisible = true;
  }

  /**
   * ----------------------------------------------------------------
   * ohter
   * ----------------------------------------------------------------
   */
  modalTimeChange(result: any, key: string) {
    // console.log('dads', result);
  }

  // 查询品牌List
  async queryBrandOption() {
    const params = {
      page: 1,
      pageSize: 99999
    }
    this.brandOptions = [];
    const {code, data, message}: any = await this.commonService.getBrandList(params);
    this.brandOptions = data?.records || [];
  }

  // 品牌change
  brandModelChange(val: any) {
    this.validateForm.get('seriesId')?.setValue('');
    this.validateForm.get('modelId')?.setValue('');
    this.validateForm.get('color')?.setValue('');
    this.validateForm.get('memory')?.setValue('');

    this.seriesOptions = [];
    this.modelOptions = [];
    this.colorOptions = [];
    this.memoryOptions = [];
    if (this.validateForm.value.typeId) {
      this.querySeriesOption();
      let brandObj = this.brandOptions.find((item: any) => item.id === val);
      this.validateForm.get('typeName')?.setValue(brandObj?.name || '');
    }
  }

  // 查询系列List
  async querySeriesOption() {
    const params = {
      brandId: this.validateForm.value.typeId,
      page: 1,
      pageSize: 99999
    }
    this.seriesOptions = [];
    const {code, data, message}: any = await this.commonService.getSeriesList(params);
    this.seriesOptions = data?.records || [];
  }

  // 系列change
  seriesModelChange(val: any) {
    this.validateForm.get('modelId')?.setValue('');
    this.validateForm.get('color')?.setValue('');
    this.validateForm.get('memory')?.setValue('');
    
    this.modelOptions = [];
    this.colorOptions = [];
    this.memoryOptions = [];

    if (this.validateForm.value.seriesId) {
      this.queryModelOption();
      let seriesObj = this.seriesOptions.find((item: any) => item.id === val);
      this.validateForm.get('seriesName')?.setValue(seriesObj?.name || '');
    }
  }

  // 查询机型List
  async queryModelOption() {
    const params = {
      seriesId: this.validateForm.value.seriesId,
      page: 1,
      pageSize: 99999
    }
    this.modelOptions = [];
    const {code, data, message}: any = await this.commonService.getModelList(params);
    this.modelOptions = data?.records || [];
  }

  // 机型change
  modelModelChange(val: any) {
    this.validateForm.get('color')?.setValue('');
    this.validateForm.get('memory')?.setValue('');
    this.colorOptions = [];
    this.memoryOptions = [];

    let modelObj: any = this.modelOptions.find((item: any) => item.id === val);
    this.colorOptions = modelObj?.color ? modelObj?.color.split(',') : [];
    this.memoryOptions = modelObj?.memory ? modelObj?.memory.split(',') : [];
    this.validateForm.get('modelName')?.setValue(modelObj?.name || '');
  }

  // Upload Change
  uploadHandleChange(ev: any) {
    const { originFileObj }: any = ev?.file;
    this.uploadInterface(originFileObj);
  }

  // Upload Interface 
  async uploadInterface(file: File) {
    if (!file || this.uploadLoading) {
      return
    }

    this.uploadLoading = true;
    const res: any = await this.commonService.uploadFileData(file, 'rent-plane');
    this.uploadLoading = false;
    if (res.code == 0) {
      this.message.success('上传成功');
      this.fileList.push({
        name: file.name,
        url: res.data
      })
    } else {
      this.message.error(res.message);
    }
  }

  deleFile(index: number) {
    this.fileList.splice(index, 1);
  }
}
